/******************************************************************************
 *  Author:     Williams, Jacob (williamsj@msoe.edu)
 *  Class:      CE-3910
 *  Instructor: Dr. Barnekow
 *****************************************************************************/
#include "twi.h"

/**
 * Init function for the TWI interface
 */
void TWIinit(void){

	TWBR = 72;

}

/**
 * This function performs the actions needed by every TWO operation.
 *	1. Clears TWINT
 *	2. Enables TWI system
 *	3. Performs addition commands
 *
 *	Param:		command	- The command to execute
 *	Returns: 	Status of the operation (TWSR)
 */
uint8_t TWIaction(uint8_t command){

	TWCR = (command) | (1<<TWINT) | (1<<TWEN);

	if( command != (1<<TWSTO) ){
	
		while(!(TWCR&(1<<TWINT)));

	}else{

		while(!(TWCR&(1<<TWSTO)));

	}
	
	return TW_STATUS;


}

/**
 * Reads the contents of the specified register
 *	
 *	Param:		regNumber - The register to retrieve the contents from
 *	Returns: 	The value in the specified register
 */
uint8_t TWIread(uint8_t regNumber){

	uint8_t data;

	if( !TWIaction(1<<TWSTA) == TW_START ){

		// handle error

	}

	TWDR = Camera_Read_Address;

	if( !TWIaction(0) == TW_MT_SLA_ACK ){

		// handle error

	}

	TWDR = regNumber;

	if( !TWIaction(0) == TW_MT_DATA_ACK ){

		// handle error

	}

	data = TWDR;

	TWIaction((1<<TWSTO));

	return data;

}

/**
 * Writes the specified value to the specified register
 *
 *	Param:		regNumber - The register to set the contents of
 *	Param:		value - The value to set the specified value to	
 */
void TWIwrite(uint8_t regNumber, uint8_t value){

	TWIaction(1<<TWSTA);

	TWDR = Camera_Write_Address;
	TWIaction(0);

	TWDR=regNumber;	// Address and write instruction
	TWIaction(0);

	TWDR = value;
	TWIaction(0);

	TWIaction(1<<TWSTO);

}
